import React, { useState } from 'react';
import {Form, Input, Button, Table, Modal, Select, Tag, Card, Row, Col, Switch, Divider, Popconfirm, message} from 'antd';
import {PlusOutlined, EditOutlined, DeleteOutlined, ArrowRightOutlined} from '@ant-design/icons';

const { Option } = Select;

const ApprovalFlowBuilder = () => {
    // 状态管理
    const [nodes, setNodes] = useState([]);
    const [IsModalVisible,setIsModalVisible] = useState(false);
    const [currentNode, setCurrentNode] = useState(null);
    const [form] = Form.useForm();

    // 审批人选项（模拟数据）
    const approverOptions = [
        { id: 'user', name: '发起人' },
        { id: 'user1', name: '张三' },
        { id: 'user2', name: '李四' },
        { id: 'user3', name: '王五' },
        { id: 'user4', name: '赵六' },
        { id: 'user5', name: '钱七' },
    ];

    // 节点类型选项
    const nodeTypeOptions = [
        { value: 'start', label: '开始节点' },
        { value: 'approval', label: '审批节点' },
        { value: 'end', label: '结束节点' },
        { value: 'pigeonhole', label: '归档节点' },
    ];

    // 退回选项
    const rejectOptions = [
        { value: 'previous', label: '退回上一节点' },
        { value: 'start', label: '退回开始节点' },
        { value: 'specific', label: '退回指定节点' },
    ];

    // 打开节点编辑模态框
    const showNodeModal = (node = null) => {
        setCurrentNode(node);
        if (node) {
            form.setFieldsValue({
                name: node.name,
                type: node.type,
                approvers: node.approvers,
                allowReject: node.allowReject,
                rejectType: node.rejectType,
                rejectNode: node.rejectNode
            });
        } else {
            form.resetFields();
        }
        setIsModalVisible(true);
    };

    // 保存节点
    const handleSaveNode = () => {
        form.validateFields().then(values => {
            const newNodes = [...nodes];

            if (currentNode) {
                // 更新现有节点
                const index = newNodes.findIndex(n => n.id === currentNode.id);
                newNodes[index] = { ...currentNode, ...values };
            } else {
                // 添加新节点
                const newNode = {
                    id: `node-${Date.now()}`,
                    ...values,
                    position: nodes.length + 1
                };
                newNodes.push(newNode);
            }

            setNodes(newNodes);
            setIsModalVisible(false);
            message.success(currentNode ? '节点更新成功' : '节点添加成功').then(() => {
                // 在这里编写你希望在消息关闭后执行的逻辑
                console.log('消息已关闭，可以执行后续操作');
            });

        });
    };

    // 删除节点
    const handleDeleteNode = (id) => {
        setNodes(nodes.filter(node => node.id !== id));
        message.success('节点删除成功').then(() => {console.log('节点删除成功，可以执行后续操作');});
    };

    // 列定义
    const columns = [
        {
            title: '节点名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: type => {
                const typeNames = {
                    start: '开始',
                    approval: '审批',
                    condition: '条件',
                    end: '结束'
                };
                const colors = {
                    start: 'blue',
                    approval: 'green',
                    condition: 'orange',
                    end: 'red'
                };
                return <Tag color={colors[type]}>{typeNames[type] || type}</Tag>;
            }
        },
        {
            title: '审批人',
            dataIndex: 'approvers',
            key: 'approvers',
            render: approvers => (
                <div>
                    {approvers && approvers.length > 0 ? (
                        approvers.map(id => {
                            const approver = approverOptions.find(a => a.id === id);
                            return approver ? <Tag key={id}>{approver.name}</Tag> : null;
                        })
                    ) : <Tag>无需审批</Tag>}
                </div>
            )
        },
        {
            title: '退回机制',
            dataIndex: 'allowReject',
            key: 'allowReject',
            render: (allowReject, record) => (
                allowReject ? (
                    <div>
                        <Tag color="orange">开启</Tag>
                        {record.rejectType === 'specific' && record.rejectNode && (
                            <span>退至: {nodes.find(n => n.id === record.rejectNode)?.name}</span>
                        )}
                    </div>
                ) : <Tag color="default">关闭</Tag>
            )
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <div>
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => showNodeModal(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定删除此节点吗？"
                        onConfirm={() => handleDeleteNode(record.id)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="link" danger icon={<DeleteOutlined />}>删除</Button>
                    </Popconfirm>
                </div>
            )
        }
    ];

    return (
        <div className="approval-flow-builder">
            <Card
                title="审批流程设计"
                // bordered={false}
                variant={false}
                extra={
                    <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => showNodeModal()}
                    >
                        添加节点
                    </Button>
                }
            >
                <Row gutter={[16, 16]}>
                    <Col span={24}>
                        <div className="flow-visualization">
                            <div className="flow-container">
                                {nodes.length === 0 ? (
                                    <div className="empty-flow">
                                        <p>请添加审批节点开始设计流程</p>
                                    </div>
                                ) : (
                                    nodes.map((node, index) => (
                                        <React.Fragment key={node.id}>
                                            <div className="flow-node">
                                                <div className="node-header">
                                                    <Tag color={
                                                        node.type === 'start' ? 'blue' :
                                                            node.type === 'approval' ? 'green' :
                                                                node.type === 'condition' ? 'orange' : 'red'
                                                    }>
                                                        {node.type === 'start' ? '开始' :
                                                            node.type === 'approval' ? '审批' :
                                                                node.type === 'condition' ? '条件' : '结束'}
                                                    </Tag>
                                                    <span className="node-name">{node.name}</span>
                                                    {node.allowReject && (
                                                        <Tag color="orange" style={{ marginLeft: 8 }}>可退回</Tag>
                                                    )}
                                                </div>
                                                <div className="node-body">
                                                    {node.approvers && node.approvers.length > 0 ? (
                                                        <div className="approvers">
                                                            {node.approvers.map(id => {
                                                                const approver = approverOptions.find(a => a.id === id);
                                                                return approver ? <Tag key={id}>{approver.name}</Tag> : null;
                                                            })}
                                                        </div>
                                                    ) : <div className="no-approver">无需审批</div>}
                                                </div>
                                                <div className="node-actions">
                                                    <Button
                                                        size="small"
                                                        icon={<EditOutlined />}
                                                        onClick={() => showNodeModal(node)}
                                                    />
                                                    <Popconfirm
                                                        title="确定删除此节点吗？"
                                                        onConfirm={() => handleDeleteNode(node.id)}
                                                        okText="确定"
                                                        cancelText="取消"
                                                    >
                                                        <Button size="small" danger icon={<DeleteOutlined />} />
                                                    </Popconfirm>
                                                </div>
                                            </div>
                                            {index < nodes.length - 1 && (
                                                <div className="flow-arrow">
                                                    <ArrowRightOutlined />
                                                </div>
                                            )}
                                        </React.Fragment>
                                    ))
                                )}
                            </div>
                        </div>
                    </Col>

                    <Col span={24}>
                        <Divider />
                        <Table
                            dataSource={nodes}
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                        />
                    </Col>

                    <Col span={24} style={{ marginTop: 24, textAlign: 'right' }}>
                        <Button type="primary" size="large" style={{ marginRight: 16 }}>
                            保存流程
                        </Button>
                        <Button size="large">
                            取消
                        </Button>
                    </Col>
                </Row>
            </Card>

            {/* 节点编辑模态框 */}
            <Modal
                title={currentNode ? "编辑审批节点" : "添加审批节点"}
                open={IsModalVisible}
                onOk={handleSaveNode}
                onCancel={() => setIsModalVisible(false)}
                width={600}
                // destroyOnClose
                destroyOnHidden={true}
            >
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{
                        allowReject: false,
                        type: 'approval'
                    }}
                >
                    <Form.Item
                        label="节点名称"
                        name="name"
                        rules={[{ required: true, message: '请输入节点名称' }]}
                    >
                        <Input placeholder="例如：部门主管审批" />
                    </Form.Item>

                    <Form.Item
                        label="节点类型"
                        name="type"
                        rules={[{ required: true, message: '请选择节点类型' }]}
                    >
                        <Select placeholder="请选择节点类型">
                            {nodeTypeOptions.map(option => (
                                <Option key={option.value} value={option.value}>
                                    {option.label}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="审批人"
                        name="approvers"
                        rules={[{ required: true, message: '请选择审批人' }]}
                    >
                        <Select
                            mode="multiple"
                            placeholder="请选择审批人"
                            optionFilterProp="children"
                            showSearch
                            filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {approverOptions.map(user => (
                                <Option key={user.id} value={user.id}>
                                    {user.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Divider>流程控制</Divider>

                    <Form.Item
                        label="允许退回"
                        name="allowReject"
                        valuePropName="checked"
                    >
                        <Switch />
                    </Form.Item>

                    <Form.Item
                        noStyle
                        shouldUpdate={(prevValues, currentValues) =>
                            prevValues.allowReject !== currentValues.allowReject
                        }
                    >
                        {({ getFieldValue }) => getFieldValue('allowReject') ? (
                            <>
                                <Form.Item
                                    label="退回类型"
                                    name="rejectType"
                                    rules={[{ required: true, message: '请选择退回类型' }]}
                                >
                                    <Select placeholder="请选择退回类型">
                                        {rejectOptions.map(option => (
                                            <Option key={option.value} value={option.value}>
                                                {option.label}
                                            </Option>
                                        ))}
                                    </Select>
                                </Form.Item>

                                <Form.Item
                                    noStyle
                                    shouldUpdate={(prevValues, currentValues) =>
                                        prevValues.rejectType !== currentValues.rejectType
                                    }
                                >
                                    {({ getFieldValue }) => getFieldValue('rejectType') === 'specific' ? (
                                        <Form.Item
                                            label="退回至节点"
                                            name="rejectNode"
                                            rules={[{ required: true, message: '请选择退回节点' }]}
                                        >
                                            <Select placeholder="请选择退回节点">
                                                {nodes
                                                    .filter(node => node.id !== (currentNode?.id || ''))
                                                    .map(node => (
                                                        <Option key={node.id} value={node.id}>
                                                            {node.name}
                                                        </Option>
                                                    ))}
                                            </Select>
                                        </Form.Item>
                                    ) : null}
                                </Form.Item>
                            </>
                        ) : null}
                    </Form.Item>
                </Form>
            </Modal>

<style jsx >{`
        .approval-flow-builder {
          padding: 20px;
        }
        .flow-visualization {
          background-color: #f9f9f9;
          border-radius: 8px;
          padding: 20px;
          margin-bottom: 20px;
          border: 1px solid #eee;
        }
        .flow-container {
          display: flex;
          align-items: center;
          justify-content: center;
          flex-wrap: wrap;
          min-height: 150px;
        }
        .flow-node {
          background: white;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          padding: 12px;
          width: 200px;
          box-shadow: 0 2px 8px rgba(0,0,0,0.09);
          position: relative;
        }
        .node-header {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          padding-bottom: 8px;
          border-bottom: 1px solid #f0f0f0;
        }
        .node-name {
          margin-left: 8px;
          font-weight: 500;
        }
        .node-body {
          min-height: 40px;
        }
        .approvers {
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
        }
        .no-approver {
          color: #999;
          font-size: 12px;
        }
        .node-actions {
          position: absolute;
          top: 12px;
          right: 12px;
        }
        .flow-arrow {
          padding: 0 15px;
          color: #aaa;
          font-size: 18px;
        }
        .empty-flow {
          text-align: center;
          color: #999;
          padding: 40px 0;
        }
        .ant-divider {
          margin: 16px 0;
        }
      `}</style>
        </div>
    );
};

export default ApprovalFlowBuilder;